package logic

import (
	"context"
	"fmt"
	"market/model/mysql"
	"market/model/redis"
	"market/pkg"

	"market/marketrpc/internal/svc"
	"market/marketrpc/marketrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserRegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserRegisterLogic {
	return &UserRegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UserRegisterLogic) UserRegister(in *marketrpc.UserRegisterRequest) (*marketrpc.UserRegisterResponse, error) {
	// todo: add your logic here and delete this line
	get := redis.Client.Get("Smsregister" + in.Phone)
	if get.Val() != in.Sms {
		return nil, fmt.Errorf("当前验证码错误")
	}
	var finduser mysql.User
	mysql.DB.Debug().Where("phone =?", in.Phone).Find(&finduser)
	if finduser.ID != 0 {
		return nil, fmt.Errorf("当前面账号已被注册请重新输入")
	}
	user := mysql.User{
		Name:     in.Name,
		Phone:    in.Phone,
		Password: pkg.Md5Password(in.Password),
	}
	mysql.DB.Debug().Create(&user)
	return &marketrpc.UserRegisterResponse{Id: int64(user.ID)}, nil
}
